<template>
    <div>

        <div style="margin: 20px">
            <a-button type="primary" icon="backward" @click="toMyApply">我的报名</a-button>
        </div>
        <!--商品列表-->
        <div>
            <a-card title="请选择秒杀商品SKU">
                <div>
                    <a-form-model>
                        <a-row>
                            <a-col :span="6">
                                <a-form-model-item label="商品名：">
                                    <a-input v-model="searchData.title"/>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="6" :offset="3">
                                <a-form-model-item label="商品编号：">
                                    <a-input v-model="searchData.goodsId"/>
                                </a-form-model-item>
                            </a-col>

                        </a-row>
                        <a-button style="color: #E2231A" @click="loadData">搜索</a-button>
                        <a-button style="color: gray" @click="resetSearch">重置</a-button>

                    </a-form-model>
                </div>
                <a-table rowKey="id" :pagination="false" size="small" :columns="columns" :data-source="goodsData"
                         class="components-table-demo-nested">
            <span slot="operation" slot-scope="record">
<!--                <a><a-icon type="edit" @click="editGoods(record)"></a-icon></a>-->
                <!--                <a-button type="link" v-if="record.onSell===1">下架商品</a-button>-->

            </span>
                    <a slot="createTime" slot-scope="record" style="color: black">{{moment(record.createTime).format("YYYY-MM-DD HH:mm:ss")}}</a>
                    <a v-if="columns.find(item=>item.dataIndex==='deleteTime')" slot="deleteTime" slot-scope="record"
                       style="color: black">{{moment(record.deleteTime).format("YYYY-MM-DD HH:mm:ss")}}</a>
                    <span slot="onSell" slot-scope="text" style="color: black">
                <a-tag :color="text===1?'blue':''">{{text===1?'出售中':'仓库中'}}</a-tag>
            </span>
                    <span slot="status" slot-scope="text,record" style="color: black">
<!--                1有效/已审核 0 无效 2 待审核(第一次发布) 3 待审核（商品修改）-->
                <a-tag :color="record.status===1?'green':record.status===0?'red':(record.status===2||record.status===3)?'blue':''">{{record.status===1?'审核通过(有效)':record.status===0?'审核未通过':(record.status===2||record.status===3)?'待审核':'未知'}}</a-tag>
            </span>
                    <span slot="brand" slot-scope="record">
                <img v-if="record.logo" :src="record.logo">
                <span v-else>{{record.name}}</span>
            </span>
                    <a-table
                            rowKey="id"
                            align="center"
                            size="small"
                            slot="expandedRowRender"
                            slot-scope="record"
                            :row-selection="{ selectedRowKeys: skuSelectedRowKeys, onChange:(selectedRowKeys, selectedRows)=> onChangeBack(selectedRowKeys, selectedRows,record) }"
                            :columns="innerColumns"
                            :data-source="record.goodsSkuList"
                            :pagination="false"
                    >
                <span slot="pictures" slot-scope="text">
                    <img style="width: 70px;height: 70px" :src="text">
                </span>
                        <span slot="spec" slot-scope="text">{{text}} </span>
                        <span slot="valid" slot-scope="text"> <a-badge :color="text===1?'green':'red'"/>{{text===1?'售卖中':'失效'}} </span>

                    </a-table>
                </a-table>
                <a-pagination showQuickJumper v-model="pageMap.page" :page-size="pageMap.size"
                              :total="pageMap.total" @change="pageChange"/>
            </a-card>

        </div>

        <div>
            <a-card title="报名信息" style="margin-bottom: 30px;">
                <a-form-model ref="formApply" layout="horizontal"
                              :rules="applyFormRules"
                              :model="applyData"
                              style="margin-bottom: 20px">
                    <a-row :gutter="16">

                        <a-col :span="8" :offset="0">
                            <a-form-model-item label="参与活动" prop="activityId">
                                <a-select disabled v-model="applyData.activityId" style="width: 300px">
                                    <a-select-option :value="item.id+''" v-for="item in activityData">{{item.name}}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                            <a-form-model-item hidden label="排期id" prop="scheduleId">
                                <a-input
                                        v-model=applyData.scheduleId
                                        type="text"
                                >
                                </a-input>
                            </a-form-model-item>

                        </a-col>
                        <a-col :span="8">

                            <a-form-model-item label="商品统一折扣">
                                <a-input-number
                                        style="width: 200px"
                                        :min="1"
                                        :max="9"
                                        v-model="applyData.discount"
                                        :formatter="value => `${value}折`"
                                        :parser="value => value.replace('折', '')"
                                        @change="allDiscountChange"
                                />
                            </a-form-model-item>

                        </a-col>
                    </a-row>

                    <a-row :gutter="16">

                    </a-row>

                </a-form-model>

            </a-card>

        </div>


        <a-card style="clear: right;" title="已选商品：">

        </a-card>
        <!--已选商品-->
        <div style="margin-bottom: 20px;">
            <a-card v-for="(skuInfo,key,index) in selectedSkus" :title="'商品编号：'+key" style="margin-top: 13px">
                <template slot="actions" class="ant-card-actions">
                    <div>折扣：
                        <a-input-number
                                style="width: 200px"
                                :min="1"
                                :max="9"
                                v-model="goodsDiscount[key]"
                                :formatter="value => `${value}折`"
                                :parser="value => value.replace('折', '')"
                        />

                    </div>
                </template>
                <a-row class="address-row" style="margin-bottom: 20px">
                    <a-col :span="10">
                        <div style="font-size: 13px">
                        </div>
                    </a-col>
                    <a-col :span="4" :offset="2">
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px;font-weight: 700">
                            库存
                        </div>
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px;font-weight: 700">
                            折后价格
                        </div>
                    </a-col>
                </a-row>
                <a-row class="address-row" v-for="sku in skuInfo">
                    <a-col :span="10">
                        <div style="font-size: 13px">
                            {{sku.name}}
                        </div>
                    </a-col>
                    <a-col :span="4" :offset="2">
                        <img style="width: 70px;height: 70px" :src="sku.pic">
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px">
                            <span style="color: black">{{sku.stock}}</span>
                        </div>
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px">
                            <span style="color: red">{{Math.floor(sku.price*goodsDiscount[key]*0.1)+".00"}}</span>
                        </div>
                    </a-col>
                </a-row>


            </a-card>

        </div>

        <!--申请非法，展示已申请过的sku提示，让商家移除-->
        <div style="margin-bottom: 20px;">
            <a-card v-for="(sku,index) in appliedSkus" title="以下商品已申请过当前活动当前排期请移除后重新申请:" style="margin-top: 13px">
                <a-row class="address-row" style="margin-bottom: 20px">
                    <a-col :span="10">
                        <div style="font-size: 13px">
                        </div>
                    </a-col>
                    <a-col :span="4" :offset="2">
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px;font-weight: 700">
                            库存
                        </div>
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px;font-weight: 700">
                            折后价格
                        </div>
                    </a-col>
                </a-row>
                <a-row class="address-row">
                    <a-col :span="10">
                        <div style="font-size: 13px">
                            {{sku.name}}
                        </div>
                    </a-col>
                    <a-col :span="4" :offset="2">
                        <img style="width: 70px;height: 70px" :src="sku.pic">
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px">
                            <span style="color: black">{{sku.stock}}</span>
                        </div>
                    </a-col>
                    <a-col :span="4">
                        <div style="font-size: 16px">
                            <span style="color: red">{{Math.floor(sku.price*goodsDiscount[key]*0.1)+".00"}}</span>
                        </div>
                    </a-col>
                </a-row>


            </a-card>

        </div>

        <div class="bottom-commit">
            <a-button class="bottom-btn" type="primary" @click="applyCommit">申请
            </a-button>
        </div>
    </div>
</template>

<script>

    import killApplyApi from "../../../api/remarketing/killApplyApi";

    const columns = [
        {title: '宝贝', dataIndex: 'name', width: 250},
        {title: '品牌', dataIndex: 'brand', width: 150, scopedSlots: {customRender: 'brand'}, align: 'center'},
        {title: '分类', dataIndex: 'category', width: 250},
        {title: '创建时间', dataIndex: 'createTime', width: 150, scopedSlots: {customRender: 'createTime'}},
        {title: '销量', dataIndex: 'sellCount', align: 'center', width: 100},
        {title: '出售状态', dataIndex: 'onSell', align: 'center', width: 100, scopedSlots: {customRender: 'onSell'}},
        {title: '商品状态', dataIndex: 'status', align: 'center', width: 100, scopedSlots: {customRender: 'status'}},
        {title: '操作', key: 'operation', scopedSlots: {customRender: 'operation'}, align: 'center'},
    ];
    const innerColumns = [
        {title: '图片', dataIndex: 'pictures', scopedSlots: {customRender: 'pictures'}, align: 'center'},
        {title: '规格', dataIndex: 'spec', width: 180, scopedSlots: {customRender: 'spec'}, align: 'center'},
        {title: '库存', dataIndex: 'stock', width: 100, align: 'center'},
        {title: '价格', dataIndex: 'price', align: 'center'},
        {title: '状态', dataIndex: 'valid', scopedSlots: {customRender: 'valid'}, align: 'center'},
        {title: '积分赠送', dataIndex: 'integral', key: 'name', align: 'center'},
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            scopedSlots: {customRender: 'operation'},
        },
    ];


    import goodsApi from "../../../api/goods/goodsApi";
    import moment from 'moment-timezone'
    import cateApi from "../../../api/cateApi";
    import {getUrlParam} from "../../../utils/urlUtils";
    import activityApi from "../../../api/remarketing/activityApi";

    export default {
        name: "applyKillGoods",
        inject: ["reload"],
        data() {
            return {
                columns,
                innerColumns,
                goodsData: [],
                pageMap: {
                    page: 1,
                    size: 8,
                    total: 0
                },
                searchData: {
                    title: "",
                    status: 1,
                    onSell: "1",
                    goodsId: "",
                    activityId: undefined,
                    scheduleId: undefined,

                },
                activityData: [],

                //表单
                applyData: {
                    activityId: undefined,
                    scheduleId: undefined,
                    discount: 5,
                },
                appliedSkus: [],//如果存在已经申请的sku，则在这里存储展示出来【除非网络或接口阻塞，否则当前查询出来的商品列表不会展示申请过的sku】
                selectedSkus: {},//选中的秒杀商品信息 格式[{goodsId:[{id,name,pic,stock,price...(sku信息)}]}]
                goodsDiscount: {},
                skuSelectedRowKeys: [],
                applyFormRules: {
                    name: [
                        {required: true, message: '请输入分类名', trigger: 'blur'}
                    ],
                    mobileName: [
                        {required: true, message: '请输入手机端名称', trigger: 'blur'}
                    ],
                    pidTemp: [{required: true, message: '请选择上级分类', trigger: 'blur'}],
                },
            }
        },

        created() {
            let urlParam = getUrlParam();
            this.loadActivityList()
            if (urlParam && urlParam.ac && urlParam.schId) {
                this.applyData.activityId = urlParam.ac + ""
                this.searchData.activityId = urlParam.ac + ""
                this.applyData.scheduleId = urlParam.schId
                this.searchData.scheduleId = urlParam.schId
            }

            this.loadData()
        },
        methods: {
            moment,


            pageChange(current) {
                this.pageMap.page = current;
                this.loadData()
            },
            loadData() {
                goodsApi.shopGoodsList(this.searchData, this.pageMap.page, this.pageMap.size).then(resp => {
                    if (resp.data.flag) {
                        this.goodsData = resp.data.data.rows;
                        this.pageMap.total = resp.data.data.total;
                    }
                })
            },
            resetSearch() {
                this.reload()
            },
            /**
             * 加载全部活动的列表
             */
            loadActivityList() {
                activityApi.list().then(resp => {
                    if (resp.data.flag) {
                        this.activityData = resp.data.data
                    }
                })
            },
            /**
             * 统一折扣改变，修改所有已选商品的折扣
             */
            allDiscountChange(value) {
                if (value >= 1 && value <= 9) {
                    if (this.goodsDiscount) {
                        for (let key in this.goodsDiscount) {
                            console.log(key)
                            this.goodsDiscount[key] = value;
                        }
                    }
                    this.applyData.discount = value;
                }
            },

            /**
             * 提交申请
             */
            applyCommit() {
                console.log(this.selectedSkus)
                console.log(this.goodsDiscount)
                console.log(this.applyData)
                if (!this.applyData.activityId || !this.applyData.scheduleId) {
                    this.$message.warning("尚未选中活动和排期！");
                    return;
                }
                let values = Object.values(this.selectedSkus);
                if (values.length <= 0) {
                    this.$message.warning("请选择参与秒杀的Sku商品")
                    return;
                }

                let killApplyList = []
                let activityId = this.applyData.activityId;
                let scheduleId = this.applyData.scheduleId;
                let selectedSkus = JSON.parse(JSON.stringify(this.selectedSkus))

                for (let goodsId in selectedSkus) {
                    console.log("kucun")
                    console.log(selectedSkus[goodsId][0].sellCount)
                    let killApply = {
                        activityId: activityId,
                        goodsId: goodsId,
                        sellCount: selectedSkus[goodsId][0].sellCount,//todo
                        discount: this.goodsDiscount[goodsId],
                        scheduleId: scheduleId,
                    }
                    let skus = selectedSkus[goodsId];
                    //删除掉暂存的商品销量信息
                    skus.forEach(sku => delete sku.sellCount)

                    killApply.params = JSON.stringify(skus)
                    killApplyList.push(killApply)

                }
                console.log("申请信息：" + killApplyList)
                killApplyApi.commitApply(killApplyList).then(resp => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message)
                        this.reload()
                    } else if (resp.data.data && resp.data.data != null) {
                        this.appliedSkus = resp.data.data
                    }
                })


            },
            /**
             * 表格选中行的回调
             * */
            onChangeBack(selectedRowKeys, selectedRows, record) {
                console.log(record)
                this.skuSelectedRowKeys = selectedRowKeys
                if (selectedRows && selectedRows.length > 0) {
                    let skus = []
                    selectedRows.forEach(row => {
                        let sku = {
                            id: row.id,
                            name: row.name,
                            pic: row.pictures,
                            price: row.price,
                            stock: row.stock,
                            sellCount: record.sellCount
                        }
                        skus.push(sku)
                    })
                    //每个商品sku都是独立的表格，因此当前选中的行都是同一个商品，即goodsId都相同,这里直接覆盖掉原goodsId选中的sku
                    //因为selectedSkus内数据的key不可预支，因此需要强制刷新内部结构，否则页面无法刷新新的数据
                    this.$set(this.selectedSkus, selectedRows[0].goodsId, skus)
                    this.$set(this.goodsDiscount, selectedRows[0].goodsId, this.applyData.discount ? this.applyData.discount : 5)
                } else {
                    //当前商品一个都没选
                    if (this.selectedSkus[record.id]) {
                        //清除之前选中的
                        this.$delete(this.selectedSkus, record.id)
                        this.$delete(this.goodsDiscount, record.id)
                    }
                }

                console.log(this.selectedSkus)
            },
            toMyApply() {
                this.$router.push("/cell-center/myApply")
            }

        }

    }
</script>

<style scoped>

    .bottom-commit {
        position: fixed;
        height: 72px;
        width: 77%;
        bottom: 0px;
        text-align: center;
        border-top: #4A77FF solid 2px;
        background: white;
    }

    .bottom-btn {
        height: 40px;
        margin: 16px;
        width: 160px;
        border: #0085D7 solid 1px;
    }
</style>